package com.keba.otp.server.wsi;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.catalina.connector.Request;
import org.bouncycastle.util.encoders.Hex;

import com.keba.otp.core.Company;
import com.keba.otp.core.Tempkey;
import com.keba.otp.core.User;
import com.keba.otp.crypto.Crypto;
import com.keba.otp.db.CompaniesDAO;
import com.keba.otp.db.DAOFactory;
import com.keba.otp.db.TempkeysDAO;
import com.keba.otp.db.UsersDAO;

/**
 * A cegek bejelentkezeset es uj felhasznalok regisztalasat biztosito Servlet
 * @author ENCI
 */
public class WebServiceControl extends HttpServlet implements WebServiceInterface{
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public WebServiceControl() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action = request.getParameter("action");
		if (action != null)
			if (action.equals("logout")) logout(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action = request.getParameter("action");
		if (action != null){
			if (action.equals("login")){
				login(request.getParameter("company"),request.getParameter("passw"),request,response);
			}else if (action.equals("register")){
				registerNewUser(request.getParameter("user"), request.getParameter("passw"), request, response);
			}
		}
	}

	@Override
	public void login(String company, String passw, HttpServletRequest request, HttpServletResponse response) {
		DAOFactory daoFactory = DAOFactory.getInstance(DAOFactory.MYSQL);
		CompaniesDAO companiesDao = daoFactory.getCompaniesDAO();
		Company foundCompany;
		try{
			byte[] inBuff = company.getBytes("utf-8");
			byte[] outBuff = new byte[64];
			org.bouncycastle.crypto.digests.SHA512Digest digest = new org.bouncycastle.crypto.digests.SHA512Digest();
			digest.update(inBuff, 0, inBuff.length);
			int len = digest.doFinal(outBuff, 0);
			String hash = new String(Hex.encode(outBuff, 0, len));
		
			if ((foundCompany = companiesDao.getCompanyByHash(hash)) != null){
				
				if (foundCompany.getCompanyPass().equals(Crypto.performEncrypt(passw, foundCompany.getCompanyKey()))){
					HttpSession session = request.getSession(true);
					session.setAttribute("loggedin","true");
					response.sendRedirect("register.html");
				} else
					response.getWriter().write("<html><link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" /><div class=\"header\">Hibas felhasznalonev/jelszo. <a href=\"" + response.encodeRedirectURL("login.html") + "\">Vissza</a></div></html>");
			} else {
				response.getWriter().write("<html><link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" /><div class=\"header\">Hibas felhasznalonev/jelszo. <a href=\"" + response.encodeRedirectURL("login.html") + "\">Vissza</a></div></html>");
			}
		}catch(UnsupportedEncodingException e){
			//e.printStackTrace();
		} catch (IOException e) {
			//e.printStackTrace();
		}
	}

	@Override
	public void registerNewUser(String user, String passw, HttpServletRequest request, HttpServletResponse response) {
		//ide ellenorzes h meg bevane jelentkezve
		HttpSession session = request.getSession();
		if (session.getAttribute("loggedin") != null) {
			DAOFactory daoFactory = DAOFactory.getInstance(DAOFactory.MYSQL);
			UsersDAO usersDao = daoFactory.getUsersDAO();
			TempkeysDAO tempkeysDao = daoFactory.getTempkeysDAO();
			byte[] key = Crypto.generateKey();
			String encryptedUser = Crypto.performEncrypt(user,key);
			String encryptedPassw = Crypto.performEncrypt(passw,key);
			String tempKey = generateTempKey();
			if (usersDao.insertUser(new User(encryptedUser, null, encryptedPassw, key))) {
				tempkeysDao.insertTempkey(new Tempkey(tempKey,key));
				try {
					response.getWriter().write("<html><link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" /><div class=\"header\">Ideiglenes kulcs(tempkey):" + tempKey + "</div></html>");
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				try {
					response.getWriter().write("<html><link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" /><div class=\"header\">Ilyen felhasznalo mar letezik.<a href=\"" + response.encodeRedirectURL("register.html") + "\">Vissza</a></div></html>");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} else
			try {
				response.sendRedirect(response.encodeRedirectURL("login.html"));
			} catch (IOException e) {
				e.printStackTrace();
			}
	}

	@Override
	public void logout(HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = request.getSession();
		session.removeAttribute("loggedin");
		session.invalidate();
	}
	
	/**
	 * general egy uj ideiglenes kulcsot
	 * @return a generalt kulcs
	 */
	@Override
	public String generateTempKey() {
		return org.apache.commons.lang.RandomStringUtils.randomAlphanumeric(8);
	}
}
